<?php

namespace Home\Controller;

use Home\Model\PaymentModel;
use Think\Controller;

class MemberController extends CommonController {

    protected $memberModel;
    protected $storeModel;
    protected $orderModel;
    public function _initialize(){
        parent::_initialize();
        $this->memberModel = D("member");
        $this->storeModel = D("store");
        $this->orderModel = D("order");
    }

    //会员列表页  店铺推广展示
    public function index(){
        $post = I('');

        $start_time = $post['start_time'];
        $end_time = $post['end_time'];
        $store_parent_id = $post['store_parent_id'];
        $store_id = $post['store_id'];
        $user_name = trim($post['user_name']);
        $page = $post["p"]?$post["p"]:0;
        $pageSize = 20;

        $this->assign('start_time',$start_time);
        $this->assign('end_time',$end_time);
        $this->assign('store_parent_id',$store_parent_id);
        $this->assign("store_id",$store_id);

        //昨日时间
        $beginYesterday = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $endYesterday = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;

        $storeIds = '';
        foreach($this->storeList as $k=>$v){
            if($k == 0){
                $storeIds = $v['store_id'];
            }else{
                $storeIds .= ','.$v['store_id'];
            }
        }
        //时间条件
        if($start_time){
            $s_time = strtotime($start_time);
            $where1['reg_time'] = array("egt",$s_time);
            if($end_time){
                $e_time = strtotime($end_time);
                $where1['reg_time'] = array("between",array($s_time,$e_time));
            }
            $htime=date('H:i:s',$s_time);
            $itime=date('i',$s_time);//得到今天的分钟数
            $stime=date('s',$s_time);//得到今天的秒数
            //得到昨日的00:00:00点时间
            $beginYesterday = strtotime(date('Y-m-d H:i:s',$s_time-(24+$htime)*60*60-$itime*60-$stime));
            //得到昨天23:59:59点的时间
            $endYesterday   = strtotime(date('Y-m-d H:i:s',$s_time-($htime+1)*60*60+(59-$itime)*60+(59-$stime)));

        }else if($end_time){
            $e_time = strtotime($end_time);
            $where1['reg_time'] = array("elt",$e_time);
        }
        //店铺条件
        if($post['store_id']){
            //总店存在  需要把总店下属的分店遍历
            $store_parentList = $this->storeModel->where(array('parent_id'=>$post['store_id']))->select();
            $store_ids = '';
            if(!empty($store_parentList)){
                foreach($store_parentList as $k=>$v){
                    if($k == 0){
                        $store_ids = $post['store_id'].','.$v['store_id'];
                    }else{
                        $store_ids .= ','.$v['store_id'];
                    }
                }
            }else{
                $store_ids = $post['store_id'];
            }
            $this->assign('store_parentList',$store_parentList);
            //搜索二级店铺
            if($post['store_parent_id']){
                $where1['s_id'] = $post['store_parent_id'];
                $where2['first_class'] = $post['store_id'];
                $where2['second_class'] = $post['store_parent_id'];
                $where['_complex'] = array(
                    $where1,
                    $where2,
                    '_logic' => 'or'
                );
                $where_yesterday['_complex'] = array(
                    $where1,
                    $where2,
                    '_logic' => 'or'
                );
            }else{
                $where1['s_id'] = array('in',$store_ids);
                $where2['first_class'] = $post['store_id'];
                $where['_complex'] = array(
                    $where1,
                    $where2,
                    '_logic' => 'or'
                );
                $where_yesterday['_complex'] = array(
                    $where1,
                    $where2,
                    '_logic' => 'or'
                );
            }
        }
        $where['user_id'] = array('not in',$storeIds);
        $wholeMemberCount = $this->memberModel->where($where)->count();
        $userIds = '';
        //遍历每一个会员查出每一个会员的成交金额 以及成交数
        $wholeMemberList = $this->memberModel->where($where)->select();
        foreach($wholeMemberList as $k=>$v){
            if($k == 0){
                $userIds = $v['user_id'];
            }else{
                $userIds .= ','.$v['user_id'];
            }
        }

        $where['first_class'] = array('neq',0);
        $where['third_class'] = array('eq',0);
        //统计昨天注册会员数
        $where_yesterday['reg_time'] = array("between",array($beginYesterday,$endYesterday));
        $yesterdayCount = $this->memberModel->where($where_yesterday)->count();


        //会员名称搜索
        if($user_name){
            $where['user_name|real_name|phone_mob'] = array("like","%$user_name%");
            $this->assign("user_name",$user_name);
        }




        //会员总数及会员列表
        $count = $this->memberModel->where($where)->count();
        $list = $this->memberModel->where($where)
            ->page($page,$pageSize)
            ->order("reg_time desc")
            ->select();

        foreach($list as $key=>$value){
            $list[$key]['totalTurnover'] = 0.00;
            $orderMember['buyer_id'] = $value['user_id'];
            $orderMember['status'] = array('in',array(20,30,40));
            $list[$key]['totalNumber'] = $this->orderModel->where($orderMember)->count();
            $list[$key]['totalTurnover'] += sprintf("%.2f",$this->orderModel->where($orderMember)->sum('order_amount'));
            $where1['third_class'] = $value['user_id'];
            $list[$key]['register_number'] = $this->memberModel->where($where1)->count();
        }


        $orderWhere['buyer_id'] = array('in',$userIds);
        //查出所有会员的合计总额   以及合计金额
        $totalSales = $this->orderModel->where($orderWhere)->sum('order_amount');
        //查出所有会员的成交总额 以及成交数量
        $orderWhere['status'] = array('in',array(20,30,40));
        $totalNumber = $this->orderModel->where($orderWhere)->count();
        $totalTurnover = $this->orderModel->where($orderWhere)->sum('order_amount');

        $map['start_time'] = $start_time;
        $map['end_time'] = $end_time;
        $map['store_id'] = $store_id;
        $map['store_parent_id'] = $store_parent_id;
        $map['user_name'] = $user_name;
        if(empty($map)){
            $map = array();
        }
        $show = $this->getPage($count,$page,$pageSize,$map);

        //拼接返回数据
        $newArr = array(
            'list'           => $list,              //会员列表数据
            'yesterdayCount' => $yesterdayCount,    //昨日注册人数
            'totalSales'     => sprintf("%.2f",$totalSales),        //合计金额
            'totalNumber'    => $totalNumber,       //已成交数量
            'totalTurnover'  => sprintf("%.2f",$totalTurnover),     //已成交金额
            'count'          => $wholeMemberCount              //共新增会员数
        );
        $storeList = $this->storeModel->where(array("parent_id"=>0))->select();
        $this->assign("newArr",$newArr);
        $this->assign("storeList",$storeList);
        $this->assign("page",$show);
        $this->display();
    }

    //封装统计用户方法
    private function getMember($where){

    }
    //获取店铺
    public function getStore(){
        $store_id = I("store_id");
        $store = new StoreController();
        $list = $store->get_son_storeList($store_id);
        echo json_encode($list);
        exit();
    }


    //会员统计
    public function statement(){
        $post = I("");
        $search_arr = $this->dealwithSearchTime($post);
        //获得系统年份
        $year_arr = $this->getSystemYearArr();
        //获得系统月份
        $month_arr = $this->getSystemMonthArr();
        //获得本月的周时间段
        $week_arr = $this->getMonthWeekArr($search_arr['week']['current_year'], $search_arr['week']['current_month']);


        //店铺条件
        $storeList = $this->storeModel->where(array("parent_id"=>0))->select();
        if($post['store_id']) {
            //总店存在  需要把总店下属的分店遍历
            $store_parentList = $this->storeModel->where(array('parent_id' => $post['store_id']))->select();
            $this->assign('store_parentList',$store_parentList);
        }

        if($post['store_id']){
            $store_ids = '';
            if(!empty($store_parentList)){
                foreach($store_parentList as $k=>$v){
                    if($k == 0){
                        $store_ids = $post['store_id'].','.$v['store_id'];
                    }else{
                        $store_ids .= ','.$v['store_id'];
                    }
                }
            }else{
                $store_ids = $post['store_id'];
            }
            //搜索二级店铺
            if($post['store_parent_id']){
                $where1['s_id'] = $post['store_parent_id'];
                $where2['first_class'] = $post['store_id'];
                $where2['second_class'] = $post['store_parent_id'];
                $where['_complex'] = array(
                    $where1,
                    $where2,
                    '_logic' => 'or'
                );
                $where_yesterday['_complex'] = array(
                    $where1,
                    $where2,
                    '_logic' => 'or'
                );
            }else{
                $where1['s_id'] = array('in',$store_ids);
                $where2['first_class'] = $post['store_id'];
                $where['_complex'] = array(
                    $where1,
                    $where2,
                    '_logic' => 'or'
                );
            }
        }

        //根据周时间搜索统计
        if ($search_arr['type'] == 'week') {
            $current_weekarr = explode('|', $search_arr['week']['current_week']);
            $stime = strtotime($current_weekarr[0]) - 86400 * 7;
            $etime = strtotime($current_weekarr[1]) + 86400 - 1;
            //总计的查询时间
            $count_arr['seartime'] = ($stime + 86400 * 7) . '|' . $etime;

            $up_week = @date('W', $stime); //上周
            $curr_week = @date('W', $etime); //本周
            //构造横轴数据
            for ($i = 1; $i <= 7; $i++) {
                //统计图数据
                $up_arr[$i] = 0;
                $curr_arr[$i] = 0;
                $tmp_weekarr = $this->getSystemWeekArr();
                //统计表数据
                $currlist_arr[$i]['timetext'] = $tmp_weekarr[$i];
                //方便搜索会员列表，计算开始时间和结束时间
                $currlist_arr[$i]['stime'] = strtotime($current_weekarr[0]) + ($i - 1) * 86400;
                $currlist_arr[$i]['etime'] = $currlist_arr[$i]['stime'] + 86400 - 1;

                $uplist_arr[$i]['val'] = 0;
                $currlist_arr[$i]['val'] = 0;
                //横轴
                $stat_arr['xAxis']['data'][] = $tmp_weekarr[$i];
                unset($tmp_weekarr);
            }
            $where['reg_time'] = array("between",array($stime,$etime));
            $memberlist = $this->memberModel->where($where)
                ->field('count(*) as allnum ,WEEKOFYEAR(FROM_UNIXTIME(reg_time)) as weekval,WEEKDAY(FROM_UNIXTIME(reg_time))+1 as dayofweekval')->group('weekval,dayofweekval')->select();



            foreach ($memberlist as $k => $v) {
                if ($up_week == intval($v['weekval'])) {
                    $up_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $uplist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    $count_arr['up'] += intval($v['allnum']);
                }
                if ($curr_week == $v['weekval']) {
                    $curr_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $currlist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    $count_arr['curr'] += intval($v['allnum']);
                }
            }


            $stat_arr['series'][0]['name'] = '上周';
            $stat_arr['series'][0]['data'] = array_values($up_arr);
            $stat_arr['series'][0]['type'] = 'bar';
            $stat_arr['series'][0]['markPoint']['data'][0] = array('type'=>"max",'name'=>"最大值");
            $stat_arr['series'][0]['markPoint']['data'][1] = array('type'=>"min",'name'=>"最小值");
            $stat_arr['series'][0]['markLine']['data'][0] = array('type'=>"average",'name'=>"平均值");

            $stat_arr['series'][1]['name'] = '本周';
            $stat_arr['series'][1]['data'] = array_values($curr_arr);
            $stat_arr['series'][1]['type'] = 'bar';
            $stat_arr['series'][1]['markPoint']['data'][0] = array('type'=>"max",'name'=>"最大值");
            $stat_arr['series'][1]['markPoint']['data'][1] = array('type'=>"min",'name'=>"最小值");
            $stat_arr['series'][1]['markLine']['data'][0]  = array('type'=>"average",'name'=>"平均值");
            $this->assign('stat_json',json_encode($stat_arr));
        };
        //根据月时间搜索统计
        if ($search_arr['type'] == 'month' || $search_arr['type'] == '') {
            $stime = strtotime($search_arr['month']['current_year'] . '-' . $search_arr['month']['current_month'] . "-01 -1 month");
            $etime = $this->getMonthLastDay($search_arr['month']['current_year'], $search_arr['month']['current_month']) + 86400 - 1;
            //总计的查询时间
            $count_arr['seartime'] = strtotime($search_arr['month']['current_year'] . '-' . $search_arr['month']['current_month'] . "-01") . '|' . $etime;

            $up_month = date('m', $stime);
            $curr_month = date('m', $etime);
            //计算横轴的最大量（由于每个月的天数不同）
            $up_dayofmonth = date('t', $stime);
            $curr_dayofmonth = date('t', $etime);
            $x_max = $up_dayofmonth < $curr_dayofmonth ? $up_dayofmonth : $curr_dayofmonth;
            //构造横轴数据
            for ($i = 1; $i <= $x_max; $i++) {
                //统计图数据
                $up_arr[$i] = 0;
                $curr_arr[$i] = 0;
                //统计表数据
                $currlist_arr[$i]['timetext'] = $i;
                //方便搜索会员列表，计算开始时间和结束时间
                $currlist_arr[$i]['stime'] = strtotime($search_arr['month']['current_year'] . '-' . $search_arr['month']['current_month'] . "-01") + ($i - 1) * 86400;
                $currlist_arr[$i]['etime'] = $currlist_arr[$i]['stime'] + 86400 - 1;

                $uplist_arr[$i]['val'] = 0;
                $currlist_arr[$i]['val'] = 0;
                //横轴
                $stat_arr['xAxis']['data'][] = $i;
                unset($tmp_montharr);
            }

            $memberlist = $this->memberModel->where($where)
                ->field('count(*) as allnum ,MONTH(FROM_UNIXTIME(reg_time)) as monthval,day(FROM_UNIXTIME(reg_time)) as dayval ')
                ->group('monthval,dayval')
                ->select();

            if ($memberlist) {
                foreach ($memberlist as $k => $v) {
                    if ($up_month == $v['monthval']) {
                        $up_arr[$v['dayval']] = intval($v['allnum']);
                        $uplist_arr[$v['dayval']]['val'] = intval($v['allnum']);
                        $count_arr['up'] += intval($v['allnum']);
                    }
                    if ($curr_month == $v['monthval']) {
                        $curr_arr[$v['dayval']] = intval($v['allnum']);
                        $currlist_arr[$v['dayval']]['val'] = intval($v['allnum']);
                        $count_arr['curr'] += intval($v['allnum']);
                    }
                }
            }
            $stat_arr['series'][0]['name'] = '上月';
            $stat_arr['series'][0]['data'] = array_values($up_arr);
            $stat_arr['series'][0]['type'] = 'bar';
            $stat_arr['series'][0]['markPoint']['data'][0] = array('type'=>"max",'name'=>"最大值");
            $stat_arr['series'][0]['markPoint']['data'][1] = array('type'=>"min",'name'=>"最小值");
            $stat_arr['series'][0]['markLine']['data'][0] = array('type'=>"average",'name'=>"平均值");


            $stat_arr['series'][1]['name'] = '本月';
            $stat_arr['series'][1]['data'] = array_values($curr_arr);
            $stat_arr['series'][1]['type'] = 'bar';
            $stat_arr['series'][1]['markPoint']['data'][0] = array('type'=>"max",'name'=>"最大值");
            $stat_arr['series'][1]['markPoint']['data'][1] = array('type'=>"min",'name'=>"最小值");
            $stat_arr['series'][1]['markLine']['data'][0] = array('type'=>"average",'name'=>"平均值");
            $this->assign('stat_json',json_encode($stat_arr));
        }

        $this->assign("storeList",$storeList);
        $this->assign('search_arr',$search_arr);
        $this->assign('year_arr', $year_arr);
        $this->assign('month_arr', $month_arr);
        $this->assign('week_arr', $week_arr);
        $this->display();
    }

    /**
     * 查询每月的周数组
     */
    public function getweekofmonth() {
        $year = $_POST['y'];
        $month = $_POST['m'];
        $week_arr = $this->getMonthWeekArr($year, $month);
        echo json_encode($week_arr);
        die;
    }


    /**
     * 统计个人推广人信息
    */
    public function promoters(){
        $post = I("");
        $search_arr = $this->dealwithSearchTime($post);
        //获得系统年份
        $year_arr = $this->getSystemYearArr();
        //获得系统月份
        $month_arr = $this->getSystemMonthArr();
        //获得本月的周时间段
        $week_arr = $this->getMonthWeekArr($search_arr['week']['current_year'], $search_arr['week']['current_month']);


        //店铺条件
        $storeList = $this->storeModel->where(array("parent_id"=>2,'store_type'=>"personal"))->select();

        $where['first_class'] = 2;
        $where['second_class'] = array('neq',0);
        $where['third_class'] = array('neq',0);
        //搜索二级店铺
        if($post['store_parent_id']){
            $where1['s_id'] = $post['store_parent_id'];
            $where2['second_class'] = $post['store_parent_id'];
            $where2['third_class']  = $post['store_parent_id'];
            $where['_complex'] = array(
                $where1,
                $where2,
                '_logic' => 'or'
            );
            $where_yesterday['_complex'] = array(
                $where1,
                $where2,
                '_logic' => 'or'
            );
        }
        //根据周时间搜索统计
        if ($search_arr['type'] == 'week') {
            $current_weekarr = explode('|', $search_arr['week']['current_week']);
            $stime = strtotime($current_weekarr[0]) - 86400 * 7;
            $etime = strtotime($current_weekarr[1]) + 86400 - 1;
            //总计的查询时间
            $count_arr['seartime'] = ($stime + 86400 * 7) . '|' . $etime;

            $up_week = @date('W', $stime); //上周
            $curr_week = @date('W', $etime); //本周
            //构造横轴数据
            for ($i = 1; $i <= 7; $i++) {
                //统计图数据
                $up_arr[$i] = 0;
                $curr_arr[$i] = 0;
                $tmp_weekarr = $this->getSystemWeekArr();
                //统计表数据
                $currlist_arr[$i]['timetext'] = $tmp_weekarr[$i];
                //方便搜索会员列表，计算开始时间和结束时间
                $currlist_arr[$i]['stime'] = strtotime($current_weekarr[0]) + ($i - 1) * 86400;
                $currlist_arr[$i]['etime'] = $currlist_arr[$i]['stime'] + 86400 - 1;

                $uplist_arr[$i]['val'] = 0;
                $currlist_arr[$i]['val'] = 0;
                //横轴
                $stat_arr['xAxis']['data'][] = $tmp_weekarr[$i];
                unset($tmp_weekarr);
            }
            $where['reg_time'] = array("between",array($stime,$etime));
            $memberlist = $this->memberModel->where($where)
                ->field('count(*) as allnum ,WEEKOFYEAR(FROM_UNIXTIME(reg_time)) as weekval,WEEKDAY(FROM_UNIXTIME(reg_time))+1 as dayofweekval')->group('weekval,dayofweekval')->select();



            foreach ($memberlist as $k => $v) {
                if ($up_week == intval($v['weekval'])) {
                    $up_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $uplist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    $count_arr['up'] += intval($v['allnum']);
                }
                if ($curr_week == $v['weekval']) {
                    $curr_arr[$v['dayofweekval']] = intval($v['allnum']);
                    $currlist_arr[$v['dayofweekval']]['val'] = intval($v['allnum']);
                    $count_arr['curr'] += intval($v['allnum']);
                }
            }


            $stat_arr['series'][0]['name'] = '上周';
            $stat_arr['series'][0]['data'] = array_values($up_arr);
            $stat_arr['series'][0]['type'] = 'bar';
            $stat_arr['series'][0]['markPoint']['data'][0] = array('type'=>"max",'name'=>"最大值");
            $stat_arr['series'][0]['markPoint']['data'][1] = array('type'=>"min",'name'=>"最小值");
            $stat_arr['series'][0]['markLine']['data'][0] = array('type'=>"average",'name'=>"平均值");

            $stat_arr['series'][1]['name'] = '本周';
            $stat_arr['series'][1]['data'] = array_values($curr_arr);
            $stat_arr['series'][1]['type'] = 'bar';
            $stat_arr['series'][1]['markPoint']['data'][0] = array('type'=>"max",'name'=>"最大值");
            $stat_arr['series'][1]['markPoint']['data'][1] = array('type'=>"min",'name'=>"最小值");
            $stat_arr['series'][1]['markLine']['data'][0]  = array('type'=>"average",'name'=>"平均值");
            $this->assign('stat_json',json_encode($stat_arr));
        };
        //根据月时间搜索统计
        if ($search_arr['type'] == 'month' || $search_arr['type'] == '') {
            $stime = strtotime($search_arr['month']['current_year'] . '-' . $search_arr['month']['current_month'] . "-01 -1 month");
            $etime = $this->getMonthLastDay($search_arr['month']['current_year'], $search_arr['month']['current_month']) + 86400 - 1;
            //总计的查询时间
            $count_arr['seartime'] = strtotime($search_arr['month']['current_year'] . '-' . $search_arr['month']['current_month'] . "-01") . '|' . $etime;

            $up_month = date('m', $stime);
            $curr_month = date('m', $etime);
            //计算横轴的最大量（由于每个月的天数不同）
            $up_dayofmonth = date('t', $stime);
            $curr_dayofmonth = date('t', $etime);
            $x_max = $up_dayofmonth < $curr_dayofmonth ? $up_dayofmonth : $curr_dayofmonth;
            //构造横轴数据
            for ($i = 1; $i <= $x_max; $i++) {
                //统计图数据
                $up_arr[$i] = 0;
                $curr_arr[$i] = 0;
                //统计表数据
                $currlist_arr[$i]['timetext'] = $i;
                //方便搜索会员列表，计算开始时间和结束时间
                $currlist_arr[$i]['stime'] = strtotime($search_arr['month']['current_year'] . '-' . $search_arr['month']['current_month'] . "-01") + ($i - 1) * 86400;
                $currlist_arr[$i]['etime'] = $currlist_arr[$i]['stime'] + 86400 - 1;

                $uplist_arr[$i]['val'] = 0;
                $currlist_arr[$i]['val'] = 0;
                //横轴
                $stat_arr['xAxis']['data'][] = $i;
                unset($tmp_montharr);
            }

            $memberlist = $this->memberModel->where($where)
                ->field('count(*) as allnum ,MONTH(FROM_UNIXTIME(reg_time)) as monthval,day(FROM_UNIXTIME(reg_time)) as dayval ')
                ->group('monthval,dayval')
                ->select();
            if ($memberlist) {
                foreach ($memberlist as $k => $v) {
                    if ($up_month == $v['monthval']) {
                        $up_arr[$v['dayval']] = intval($v['allnum']);
                        $uplist_arr[$v['dayval']]['val'] = intval($v['allnum']);
                        $count_arr['up'] += intval($v['allnum']);
                    }
                    if ($curr_month == $v['monthval']) {
                        $curr_arr[$v['dayval']] = intval($v['allnum']);
                        $currlist_arr[$v['dayval']]['val'] = intval($v['allnum']);
                        $count_arr['curr'] += intval($v['allnum']);
                    }
                }
            }
            $stat_arr['series'][0]['name'] = '上月';
            $stat_arr['series'][0]['data'] = array_values($up_arr);
            $stat_arr['series'][0]['type'] = 'bar';
            $stat_arr['series'][0]['markPoint']['data'][0] = array('type'=>"max",'name'=>"最大值");
            $stat_arr['series'][0]['markPoint']['data'][1] = array('type'=>"min",'name'=>"最小值");
            $stat_arr['series'][0]['markLine']['data'][0] = array('type'=>"average",'name'=>"平均值");


            $stat_arr['series'][1]['name'] = '本月';
            $stat_arr['series'][1]['data'] = array_values($curr_arr);
            $stat_arr['series'][1]['type'] = 'bar';
            $stat_arr['series'][1]['markPoint']['data'][0] = array('type'=>"max",'name'=>"最大值");
            $stat_arr['series'][1]['markPoint']['data'][1] = array('type'=>"min",'name'=>"最小值");
            $stat_arr['series'][1]['markLine']['data'][0] = array('type'=>"average",'name'=>"平均值");
            $this->assign('stat_json',json_encode($stat_arr));
        }

        $this->assign("storeList",$storeList);
        $this->assign('search_arr',$search_arr);
        $this->assign('year_arr', $year_arr);
        $this->assign('month_arr', $month_arr);
        $this->assign('week_arr', $week_arr);
        $this->display();
    }

}


